//
//  InviteView.m
//  location
//
//  Created by Dongxiang Xu on 2025/9/11.
//

#import "InviteView.h"
#import <LinkPresentation/LinkPresentation.h>

@interface InviteView ()

@property (nonatomic,strong) UIButton *button;
@property (nonatomic,strong) UILabel *code;
@property (nonatomic,strong) UIImageView *coImg;
@property (nonatomic,strong) UILabel *time;
@property (nonatomic,strong) NSDictionary *groupInfo;

@end

@interface XDXShareItem : NSObject <UIActivityItemSource>
@property (nonatomic,strong) UIImage *image;
@property (nonatomic,copy) NSString *text;
@property (nonatomic,strong) NSURL *url;
@end

@implementation XDXShareItem
- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return self.text ?: @"";
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(UIActivityType)activityType {
    return self.text ?: @"";
}

- (LPLinkMetadata *)activityViewControllerLinkMetadata:(UIActivityViewController *)activityViewController API_AVAILABLE(ios(13.0)) {
    LPLinkMetadata *metadata = [LPLinkMetadata new];
    metadata.title = self.text ?: @"";
    if (self.url) {
        metadata.originalURL = self.url;
        metadata.URL = self.url;
    }
    if (self.image) {
        NSItemProvider *provider = [[NSItemProvider alloc] initWithObject:self.image];
        metadata.iconProvider = provider;
        metadata.imageProvider = provider;
    }
    return metadata;
}
@end

@implementation InviteView

- (instancetype)initWithFrame:(CGRect)frame
                    GroupInfo:(NSDictionary *)groupInfo
{
    self = [super initWithFrame:frame];
    if (self) {
        self.groupInfo = groupInfo;
        self.layer.masksToBounds = YES;
        [self initView];
        [self getInviteCode];
    }
    return self;
}

- (void)initView
{
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 480)];
    infoView.layer.masksToBounds = YES;
    [infoView.layer setCornerRadius:40];
    infoView.backgroundColor = RealWhiteColor;
    [self addSubview:infoView];
    
    UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(infoView.width-46, 16, 30, 30)];
    [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
    [infoView addSubview:close];
    [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
   
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, infoView.width-40, 28)];
    titleLabel.font = MEDIUM_FONT(20);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"邀请家人";
    titleLabel.textColor = RealBlackColor;
    [infoView addSubview:titleLabel];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.x, titleLabel.maxY+4, titleLabel.width, 26)];
    subTitle.font = MEDIUM_FONT(16);
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.text = [NSString stringWithFormat:@"“%@”",self.groupInfo[@"name"]];
    subTitle.textColor = RealBlackColor;
    [infoView addSubview:subTitle];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((infoView.width-120)/2, subTitle.maxY+28, 120, 120)];
    img.image = [UIImage imageNamed:@"invite"];
    [infoView addSubview:img];
    
    _button = [[UIButton alloc] initWithFrame:CGRectMake(20, img.maxY+28, infoView.width-40, 56)];
    _button.backgroundColor = LightBGColor;
    _button.layer.masksToBounds = YES;
    [_button.layer setCornerRadius:16];
    [infoView addSubview:_button];
    [[_button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        pab.string = self.code.text;
        [[HCToast shareInstance] showToast:@"复制成功"];
    }];
    
    _code = [[UILabel alloc] initWithFrame:CGRectMake((_button.width-100)/2, 0, 100, _button.height)];
    _code.font = RUBIK_BOLD_FONT(24);
    _code.textColor = RealBlackColor;
    [_button addSubview:_code];
    
    _coImg = [[UIImageView alloc] initWithFrame:CGRectMake(_code.maxX+12, (_button.height-16)/2, 16, 16)];
    _coImg.image = [UIImage imageNamed:@"copy"];
    [_button addSubview:_coImg];
    
    _time = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.x, _button.maxY+10, titleLabel.width, 18)];
    _time.font = DEFAULT_FONT(14);
    _time.textAlignment = NSTextAlignmentCenter;
    _time.textColor = [GraryHeavyLightColor colorWithAlphaComponent:0.6];
    [infoView addSubview:_time];
    
    UIButton *update = [[UIButton alloc] initWithFrame:CGRectMake(titleLabel.x, _time.maxY+28, titleLabel.width-116, 54)];
    update.layer.masksToBounds = YES;
    [update.layer setCornerRadius:27];
    update.backgroundColor = LightBGColor;
    [update setTitleColor:RealBlackColor forState:UIControlStateNormal];
    [update.titleLabel setFont:MEDIUM_FONT(16)];
    [update setTitle:@"刷新邀请码" forState:UIControlStateNormal];
    [infoView addSubview:update];
    [[update rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self updateInviteCode];
    }];
    
    UIButton *share = [[UIButton alloc] initWithFrame:CGRectMake(infoView.width-120, update.y, 100, 54)];
    share.layer.masksToBounds = YES;
    [share.layer setCornerRadius:27];
    share.backgroundColor = NormalMainColor;
    [share setImage:[UIImage imageNamed:@"share_text"] forState:UIControlStateNormal];
    [infoView addSubview:share];
    [[share rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSString *content = self.code.text;
        NSURL *url = [NSURL URLWithString:@"http://m.tanhuos.com/h5/familymap.html"];
        UIImage *image = [UIImage imageNamed:@"share_icon"];
        UIActivityViewController *con = nil;
        if (@available(iOS 13.0, *)) {
            XDXShareItem *item = [XDXShareItem new];
            item.text = content;
            item.url = url;
            item.image = image;
            con = [[UIActivityViewController alloc] initWithActivityItems:@[item] applicationActivities:nil];
        } else {
            con = [[UIActivityViewController alloc] initWithActivityItems:@[image,content,url] applicationActivities:nil];
        }
        con.completionWithItemsHandler = ^(UIActivityType activityType, BOOL completed, NSArray * returnedItems, NSError * __nullable activityError){
            
        };
        [self.parentContainerViewController presentViewController:con animated:YES completion:nil];
    }];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self insertSubview:bgView atIndex:0];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
    [bgView addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.3 animations:^{
        infoView.y = SCREEN_HEIGHT-infoView.height-32;
        self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
    }];
}

- (void)getInviteCode
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:_groupInfo[@"id"] forKey:@"groupId"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/invitationcode"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                //把字符串转为NSdate
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                dateFormatter.locale = [NSLocale systemLocale];
                dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
                NSDate *timeDate = [dateFormatter dateFromString:responseObject[@"data"][@"expireTime"]];
                
                //得到与当前时间差
                NSInteger  timeInterval = [timeDate timeIntervalSinceNow];
                if (timeInterval<1800) {
                    [self updateInviteCode];
                }else{
                    self.code.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"invitedCode"]];
                    [self.code sizeToFit];
                    [self.code setFrame:CGRectMake((self.button.width-self.code.width)/2-20, 0,  self.code.width, self.button.height)];
                    self.coImg.x = self.code.maxX+12;
                    
                    if (timeInterval>86400) {
                        self.time.text = [NSString stringWithFormat:@"验证码有效期：%d天%@",(int)timeInterval/86400,(int)timeInterval%86400/3600>0?[NSString stringWithFormat:@"%d小时",(int)timeInterval%86400/3600]:@""];
                    }else{
                        self.time.text = [NSString stringWithFormat:@"验证码有效期：%d小时",(int)timeInterval%86400/3600];
                    }
                }
            }else{
                self.code.text = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
                [self.code sizeToFit];
                [self.code setFrame:CGRectMake((self.button.width-self.code.width)/2-20, 0,  self.code.width, self.button.height)];
                self.coImg.x = self.code.maxX+12;
                self.time.text = @"验证码有效期：2天";
            }
        }else{
            [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject]];
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)updateInviteCode
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:_groupInfo[@"id"] forKey:@"groupId"];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/refreshcode"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            self.code.text = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
            [self.code sizeToFit];
            [self.code setFrame:CGRectMake((self.button.width-self.code.width)/2-20, 0,  self.code.width, self.button.height)];
            self.coImg.x = self.code.maxX+12;
            self.time.text = @"验证码有效期：2天";
        }else{
            [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject]];
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

@end
